const Koa = require('koa')
// 实例化
const app = new Koa()
const router = require('koa-router')() // 第三方的路由中间件
const bodyparser = require('koa-bodyparser')

// 定义一个内存数据库
const db = [
  {
    name: 'devin',
    pwd: "123"
  }
]



// 增删改查
router.get('/user', async (ctx, next) => {
  console.log('header参数：', ctx.request.header)
  ctx.body = db
})

router.post('/user', async (ctx, next) => {
  const postData = ctx.request.body;
  console.log(postData, 'postData')
  db.push(postData)
  ctx.body = db
})

router.put('/user/:id', async (ctx, next) => {
  let id = ctx.params.id;
  db[id] = ctx.request.body
  ctx.body = db
})

router.delete('/user/:id', async (ctx, next) => {
  let id = ctx.params.id;
  db.splice(id, 1)
  ctx.body = db
})


app.use(bodyparser()) // 帮助你解析post参数
app.use(router.routes(), router.allowedMethods())


app.listen(8000, () => {
  console.log('server port is 8000')
})